package io.gitee.cloudladder.obsidian.swagger2.plugin;

import io.gitee.cloudladder.obsidian.swagger2.annotation.ApiOperationSort;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import springfox.documentation.service.StringVendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;

import java.util.Arrays;
import java.util.Objects;

@Order(Ordered.HIGHEST_PRECEDENCE + 1000)
public class ApiOperationSortBuilderPlugin implements OperationBuilderPlugin {

    @Override
    public void apply(OperationContext operationContext) {
        int sort = Integer.MAX_VALUE;
        ApiOperationSort apiOperationSort = operationContext.getHandlerMethod().getMethodAnnotation(ApiOperationSort.class);

        if (Objects.nonNull(apiOperationSort)) {
            sort = apiOperationSort.value();
        }

        operationContext.operationBuilder().extensions(Arrays.asList(new StringVendorExtension("x-sort", String.valueOf(sort))));
    }

    @Override
    public boolean supports(DocumentationType documentationType) {
        return true;
    }

}
